<?php

namespace App\Http\Controllers\Home\Wechat;

use Illuminate\Http\Request;

use App\Http\Requests;
//use App\Http\Controllers\Controller;
use App\Models\wechat\Carts;
use App\Models\wechat\Address;
use App\Models\shop\Customer;

class AddressController extends CommonController
{
    public function __construct()
    {
        parent::__construct();

    }

    //显示地址列表
    public function index()
    {
        $address=Address::where('customer_id',$this->customer->id)->get();
//        return $address;
        return view('home.wechat.address.index')->with('address',$address);
    }
    
    //显示新增地址页面
    public function create()
    {
        return view('home.wechat.address.create');
    }
    //存储新增地址
    public function store(Request $request)
    {
//        return $request->all();
        $pca=explode(' ',$request->pca);
        Address::create([
            'customer_id' => $this->customer->id,
            'name' => $request->name,
            'province' => $pca[0],
            'city' => $pca[1],
            'area' => $pca[2],
            'tel' => $request->tel,
            'detail' => $request->detail,
        ]);
    }

    //设置默认收货地址
    public function default_address(Request $request)
    {
        Customer::where('id', $this->customer->id)->update(['address_id' => $request->address_id]);

        //重新设置session
        $customer = session()->get('customer');
        $customer['address_id'] = $request->address_id;
        session()->put('customer', $customer);
    }

    //管理我的收货地址
    public function manage()
    {
        $addresses = Address::where('customer_id', $this->customer->id)->get();
        return view('home.wechat.address.manage')->with('addresses', $addresses);
    }

    //显示编辑地址
    public function edit($id)
    {
        $address=Address::find($id);
        return view('home.wechat.address.edit')->with('address',$address);
    }
    //存储更新后的地址
    public function update(Request $request,$id)
    {
//        return $request->all();
        $pca=explode(' ',$request->pca);
        Address::where('id',$id)
            ->update([
            'customer_id' => $this->customer->id,
            'name' => $request->name,
            'province' => $pca[0],
            'city' => $pca[1],
            'area' => $pca[2],
            'tel' => $request->tel,
            'detail' => $request->detail,
        ]);
    }
    //删除地址
    public function destroy($id)
    {
        Address::destroy($id);
        return back();
    }
    
}
